package com.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 17. 电话号码的字母组合
 * 递归法回溯
 *
 * @author fy
 * @date 2022/4/21 20:21
 */
public class Solution17 {

    private List<String> res;
    private String[] map = new String[]{
            "",
            "",
            "abc",
            "def",
            "ghi",
            "jkl",
            "mno",
            "pqrs",
            "tuv",
            "wxyz"
    };

    public List<String> letterCombinations(String digits) {
        res = new ArrayList<>();
        if (digits == null || digits.length() == 0) {
            return res;
        }
        // 首先使用哈希表存储每个数字对应的所有可能的字母，然后进行回溯操作
        findCombination(digits, 0, "");
        return res;
    }

    private void findCombination(String digits, int index, String preStr) {
        // 已经搜索到最后一位字符串了, 加入集合并返回
        if (digits.length() == index) {
            res.add(preStr);
            return;
        }
        String nowStr = map[digits.charAt(index) - '0'];
        for (int i = 0; i < nowStr.length(); i++) {
            findCombination(digits, index + 1, preStr + nowStr.charAt(i));
        }
    }

    public static void main(String[] args) {
        String digits = "23";
        List<String> res = new Solution17().letterCombinations(digits);
        System.out.println(res);
    }

}
